<template>
  <div class="comment-form">
    <!-- 登录提示 -->
    <div v-if="!isLoggedIn" class="login-prompt">
      <div class="login-prompt-content">
        <IconifyIconOnline icon="ep:user" :size="20" />
        <span>请先登录后再发表评论</span>
        <el-button type="primary" size="small" @click="goToLogin">
          去登录
        </el-button>
      </div>
    </div>

    <!-- 评论输入区 -->
    <div v-else class="comment-input">
      <!-- 用户头像 -->
      <div class="user-avatar">
        <el-avatar :size="36" :src="userInfo?.avatar" :alt="userInfo?.nickName">
          <IconifyIconOnline icon="ep:user-filled" />
        </el-avatar>
      </div>

      <!-- 输入表单 -->
      <div class="input-area">
        <!-- 回复提示 -->
        <div v-if="replyTo" class="reply-hint">
          <span>回复 @{{ replyTo.nickName }}：</span>
          <el-button type="primary" text size="small" @click="cancelReply">
            取消回复
          </el-button>
        </div>

        <!-- 文本输入框 -->
        <el-input
          v-model="content"
          type="textarea"
          :placeholder="placeholder"
          :rows="3"
          :maxlength="1000"
          show-word-limit
          resize="none"
          @keydown="handleKeydown"
        />

        <!-- 操作按钮 -->
        <div class="form-actions">
          <div class="actions-left">
            <span class="input-tip">
              <IconifyIconOnline icon="ep:info-filled" :size="14" />
              支持 Ctrl+Enter 快速发布
            </span>
          </div>

          <div class="actions-right">
            <el-button v-if="content.trim()" size="small" @click="clearContent">
              清空
            </el-button>

            <el-button
              type="primary"
              size="small"
              :loading="loading"
              :disabled="!canSubmit"
              @click="handleSubmit"
            >
              {{ loading ? "发布中..." : "发布评论" }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useUserAuthStore } from "@/store/modules/userAuth";
import {
  type CreateCommentRequest,
  type UserInfo,
  UserCommentUtils
} from "@/api/user-comment";

interface Props {
  articleId: number;
  loading?: boolean;
  replyTo?: {
    commentId: number;
    userId: number;
    nickName: string;
  } | null;
}

interface Emits {
  (e: "submit", data: CreateCommentRequest): void;
  (e: "cancel-reply"): void;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  replyTo: null
});

const emit = defineEmits<Emits>();

const router = useRouter();
const userAuthStore = useUserAuthStore();

// 响应式数据
const content = ref("");

// 计算属性
const isLoggedIn = computed(() => userAuthStore.isLoggedIn);
const userInfo = computed(() => userAuthStore.userInfo);

const placeholder = computed(() => {
  if (props.replyTo) {
    return `回复 @${props.replyTo.nickName}...`;
  }
  return "写下你的评论...";
});

const canSubmit = computed(() => {
  const validation = UserCommentUtils.validateContent(content.value);
  return validation.valid && !props.loading;
});

// 方法
const handleSubmit = () => {
  if (!canSubmit.value) {
    return;
  }

  const validation = UserCommentUtils.validateContent(content.value);
  if (!validation.valid) {
    ElMessage.error(validation.message);
    return;
  }

  const commentData: CreateCommentRequest = {
    articleId: props.articleId,
    content: content.value.trim()
  };

  // 如果是回复评论
  if (props.replyTo) {
    commentData.parentId = props.replyTo.commentId;
    commentData.replyToUserId = props.replyTo.userId;
  }

  emit("submit", commentData);

  // 清空输入内容
  content.value = "";
};

const clearContent = () => {
  content.value = "";
};

const cancelReply = () => {
  emit("cancel-reply");
};

const goToLogin = () => {
  router.push("/user/login");
};

const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl+Enter 快速发布
  if (event.ctrlKey && event.key === "Enter") {
    event.preventDefault();
    handleSubmit();
  }
};
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .comment-input {
    gap: 8px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .actions-left {
    order: 2;
    text-align: center;
  }

  .actions-right {
    justify-content: flex-end;
    order: 1;
  }

  .login-prompt-content {
    flex-direction: column;
    gap: 8px;
  }
}

@media (width <= 480px) {
  .user-avatar {
    display: none;
  }

  .comment-input {
    gap: 0;
  }
}

.comment-form {
  margin-bottom: 24px;
}

.login-prompt {
  padding: 20px;
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.login-prompt-content {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.comment-input {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.user-avatar {
  flex-shrink: 0;
}

.input-area {
  flex: 1;
  min-width: 0;
}

.reply-hint {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin-bottom: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-extra-light);
  border-radius: 4px;
}

.form-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}

.actions-left {
  flex: 1;
}

.input-tip {
  display: flex;
  gap: 4px;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.actions-right {
  display: flex;
  gap: 8px;
}
</style>
